package com.fjsh.base.config.service;

import com.fjsh.bean.LoginUser;
import com.fjsh.entity.TbPermission;
import com.fjsh.entity.TbUser;
import com.fjsh.service.TbPermissionService;
import com.fjsh.service.TbUserService;
import com.google.common.collect.Lists;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

/**
 * 重写原生方法支持自定义用户信息
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private TbUserService tbUserService;
    @Resource
    private TbPermissionService tbPermissionService;

    // 将我们的用户信息和权限查询出来给oauth
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        // 此处需要调用接口查询用户信息
        TbUser tbUser = tbUserService.getUserByUserName(s);

        // 权限
        List<GrantedAuthority> grantedAuthorityList = Lists.newArrayList();
        if (tbUser!=null){
            // 获取用户权限
            List<TbPermission> permissionList = tbPermissionService.getPermissionList(tbUser.getId());
            permissionList.forEach(tbPermission -> {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(tbPermission.getEnname());
                grantedAuthorityList.add(grantedAuthority);
            });
        }

        // 直接返回用户信息给框架进行管理
        return new LoginUser(tbUser.getId(), tbUser.getUsername(), tbUser.getPassword(), true, true, true, true, grantedAuthorityList);
    }
}
